import os
import re
from typing import Pattern
import matplotlib.pyplot as plt
import pandas as pd


def compile(source_path: str, output_path: str):
    os.system("gcc -Og -pg {} -o {}".format(source_path, output_path))


def run_stat(program: str, repeat: int, event: list, output_file: str) -> dict:
    event_list_str = ",".join(event)
    os.system("perf stat -B --repeat {} -e {} -o {} ./{}".format(repeat,
                                                                 event_list_str,
                                                                 output_file,
                                                                 program))
    result_dict = analyze_stat_result(repeat, event, output_file)
    return result_dict


def analyze_stat_result(repeat: int, event: list, output_file: str) -> dict:
    result_dict = {}
    with open(output_file, "r") as f:
        result_lines = f.readlines()
    result_dict["time"] = result_lines[0][13:-1]
    result_dict["test file"] = re.compile(
        "'(.*)'").findall(result_lines[3])[0][2:]
    if repeat == 1:
        result_dict["repeat"] = 1
    else:
        result_dict["repeat"] = int(re.compile(
            r"[(](.+) runs[)]").findall(result_lines[3])[0])
    for i, event_item in enumerate(event):
        result_dict[event_item] = int(
            result_lines[5 + i][0:20].strip().replace(",", ""))
    return result_dict


if __name__ == "__main__":
    source_path = "workspace/perf_stat_example.c"
    output_path = "workspace/perf_stat_example"
    os.system("gcc -o0 {} -o {}".format(source_path, output_path))

    pi_iteration = 1000000000
    os.system("./workspace/perf_stat_example {}".format(pi_iteration))
